import { Component, OnInit, ViewChild } from '@angular/core'
import { FadeInTop } from '../../shared/animations/fade-in-top.decorator'
import { NotificationService } from '../../shared/utils/notification.service'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-weighbridge-data',
  templateUrl: './weighbridge-data.component.html',
  styleUrls: ['./weighbridge-data.css']
})
export class WeighbridgeDataComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      carNumber: {
        validators: {
          notEmpty: {
            message: '请输入车牌号码'
          }
        }
      },
      transportStartDate: {
        trigger: 'change',
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                return true
              } else {
                return {
                  valid: false,
                  message: '请选择收运开始时间'
                }
              }
            }.bind(this)
          }
        }
      },
      transportEndDate: {
        trigger: 'change',
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                return true
              } else {
                return {
                  valid: false,
                  message: '请选择收运结束时间'
                }
              }
            }.bind(this)
          }
        }
      },
      weighbridgeNetWeight: {
        validators: {
          notEmpty: {
            message: '请输入实际净重[kg]'
          }
        }
      },
      platformBucketsNum: {
        validators: {
          notEmpty: {
            message: '请输入平台桶数'
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  tabletotalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword

  searchselectedCompanyName: string = '' //公司名称
  searchselectedCompanyId: string = '' //公司ID
  selectCarNumber: string = '' // 车牌号
  selectDeviceId: string = '' // 设备ID
  startTime: string = '' //开始时间
  endTime: string = '' //结束时间
  errorRate: string = '' // 离线时长
  uploadUser: any = ''
  // uploadDate: any= ''; //上传时间
  dateType: string = '0' // 时间类型
  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowId: string = '' //批量进厂限制

  constructor(
    private jsonApiService: JsonApiService,
    private notificationService: NotificationService,
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  carDeatailUseList = carTypeListObj.carDeatailUseList

  ngOnInit() {
    this.initDate()
    // this.initAllUser().then(()=>{
    // this.selectUserName();
    this.load()
    // });
  }
  //删除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker1').val('').change()
    $('#datetimepicker2').val('').change()
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }
  // del_uploadDate(){
  //     this.uploadDate ='';
  // 	$("#uploadDate").val('').change();
  // }
  getTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

    return year + '-' + month + '-' + day
  }
  initDate() {
    var that = this
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        // common.initDatePicker('#uploadDate',1);
        $('#datetimepicker1')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeMmss(date)
            $('#datetimepicker2').datetimepicker('setStartDate', time)
          })
        $('#datetimepicker2')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeMmss(date)
            $('#datetimepicker1').datetimepicker('setEndDate', time)
          })
      })
    })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //分页回调
  tablePaginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }

  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //初始化加载list数据
  load() {
    // this.uploadDate = $('#uploadDate').val();
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.searchselectedCompanyId,
        deviceId: this.selectDeviceId,
        startTime: this.startTime ? this.startTime + ' 00:00:00' : '',
        endTime: this.endTime ? this.endTime + ' 23:59:59' : '',
        errorRate: this.errorRate,
        uploadUser: this.uploadUser,
        dateType: this.dateType,
        // uploadDate: this.uploadDate?this.uploadDate +" 00:00:00":'',
        export: '0'
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('weighbridgeVerify/V2/weighbridgeVerifyPage.html', reqdata).subscribe(data => {
      this.selected = []
      this.allChecked = false
      if (data.isSuccess) {
        for (let item of data.exhibitDatas) {
          if (item.errorRate > 10 || item.errorRate == 10) {
            item.isErrorRateRed = true
          } else {
            item.isErrorRateRed = false
          }

          if (item.errorValue) {
            item.errorValue = parseFloat(item.errorValue).toFixed(2)
          }
        }
        this.tableData = data.exhibitDatas
        this.tabletotalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //公司选中回调
  searchCompanySelected(data) {
    this.searchselectedCompanyId = data.companyId
    this.searchselectedCompanyName = data.companyName
    this.selectDeviceId = data.deviceId
    this.selectCarNumber = data.carNumber
  }
  //数据行删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'ids=' + row.id
      this.jsonApiService.http('weighbridgeVerify/V2/deleteById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        this.load()
      })
    })
  }
  // 批量删除
  batchDelete() {
    console.log(this.selected, this.rowId)
    if (this.selected.length && this.rowId != '') {
      this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
        let reqdata = 'ids=' + this.rowId
        this.jsonApiService.http('weighbridgeVerify/V2/deleteById.html', reqdata).subscribe(data => {
          this.jsonApiService.message(data.message)
          this.load()
        })
      })
    } else {
      this.jsonApiService.message('请选中最少一条数据')
    }
  }

  /**
   * 单行数据选中事件,仅支持单行选中,不支持多选
   */
  singleRowSelected(row, e, index) {
    if (
      e.target.className.includes('checkbox') ||
      e.target.className.includes('checkbox-flag') ||
      e.target.className.includes('checkbox-td') ||
      e.target.className.includes('checkbox-label')
    ) {
      this.rowSelected(row, e, index)
      return
    }
    for (let item of this.tableData) {
      item['isChecked'] = false
    }
    this.selected = []
    row.isChecked = !row.isChecked
    this.selected.push(row)
    this.rowId = row.id
  }
  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.tableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowId = ''
    } else {
      var temArr = []
      for (let item of this.tableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.rowId)
      }
      this.rowId = temArr.join(',')
    }
  }
  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowId = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.pageSize ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }

  // 数据导出
  exportData() {
    // 导出的
    // this.uploadDate = $('#uploadDate').val();
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.searchselectedCompanyId,
        deviceId: this.selectDeviceId,
        startTime: this.startTime ? this.startTime + ' 00:00:00' : '',
        endTime: this.endTime ? this.endTime + ' 23:59:59' : '',
        errorRate: this.errorRate,
        uploadUser: this.uploadUser,
        dateType: this.dateType,
        // uploadDate: this.uploadDate?this.uploadDate +" 00:00:00":'',
        export: '1'
      }
    }
    let timeCheck = common.correctTime(data.parameters, ['export', 'dateType'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'weighbridgeVerify/V2/weighbridgeVerifyPage.html')
  }

  // 导入
  fileToUpload: File = null //上传文件回调参数
  fileUp: string = ''
  //导入submit
  submitData(val) {
    let postParam = new FormData()
    postParam.append('file', this.fileToUpload)
    if (!this.fileToUpload) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    this.jsonApiService.form_http('weighbridgeVerify/V2/upload.html', postParam).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        val.hide()
        this.fileToUpload = null
        this.load()
      }
    })
  }
  //下载模板
  load_module() {
    var elemIF = document.createElement('iframe')
    elemIF.src = config.BaseURL + 'resources/template/weighbridgeVerifyV2-Template.xlsx'
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  }
  clearFile() {
    this.fileUp = ''
  }
  //文件上传change回调
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0)
    const isEXCEL =
      this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.fileToUpload.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.fileToUpload = null
      return
    }
  }
  importUp(modal) {
    this.fileToUpload = null
    modal.show()
  }
  cancelUp(val) {
    val.hide()
    this.fileToUpload = null
  }

  userList: any = [] //全部用户数据
  //擦除用户所选值
  delUserName() {
    this.uploadUser = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    // var str=$("<span class='select2-selection__placeholder'>请选择</span>");
    // $('#userNameSelect2').val("");
    // $("#select2-userNameSelect2-container").empty();
    // $("#select2-userNameSelect2-container").attr("title","");
    // $("#select2-userNameSelect2-container").prepend(str);
    this.load()
  }

  //初始化select2 选项
  selectUserName() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#userNameSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.userList, //为Select添加数据
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.uploadUser = data.text
          })
      })
    })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  //拉取
  initAllUser() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/getAllUserList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].name
            }
            selectdata[i] = obj
          }
        }
        that.userList = selectdata
        resolve()
      })
    })
  }

  // 编辑

  //初始化车辆
  select2Car() {
    var that = this
    $('#carNumberSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

        ajax: {
          url: config.BaseURL + 'stats/carListByCarNumber.html',
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: {
            withCredentials: true
          },
          data: function (params) {
            return {
              carNumber: params.term // search term
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            // 小于10个数量才判断重复
            if (data.data.length <= 10) {
              let arr = []
              let sameCar = []
              // 判断相同的车牌号
              for (let index = 0; index < data.data.length; index++) {
                let car = data.data[index]
                if (arr.indexOf(car.carNumber) != -1) {
                  sameCar.push(car.carNumber)
                } else {
                  arr.push(car.carNumber)
                }
              }
              $(data.data).each(function (index, car) {
                if (sameCar.indexOf(car.carNumber) != -1) {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber + '[' + car.parentName + ']'
                  })
                } else {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber
                  })
                }
              })
            } else {
              $(data.data).each(function (index, car) {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber
                })
              })
            }
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: this.formatRepo
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.handleRow.deviceId = data.id
        if (data.text.indexOf('[') > 0) {
          that.handleRow.carNumber = data.text.split('[')[0]
        } else {
          that.handleRow.carNumber = data.text
        }
      })
  }
  //清除车辆选中值
  del_carNumber2() {
    this.handleRow.deviceId = ''
    this.handleRow.carNumber = ''
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#carNumberInput').val('').change()
    $('#carNumberSelect2').val('')
    $('#select2-carNumberSelect2-container').empty()
    $('#select2-carNumberSelect2-container').attr('title', '')
    $('#select2-carNumberSelect2-container').prepend(str)
  }
  handleRow: any = {
    id: '',
    carNumber: '',
    deviceId: '',
    transportStartDate: '',
    transportEndDate: '',
    weighbridgeNetWeight: ''
    // platformBucketsNum: ''
  }
  editRow(row, val) {
    var that = this
    val.show()
    // this.select2Car();
    for (let item in this.handleRow) {
      this.handleRow[item] = row[item]
    }
    $('#carNumberInput').val(row.carNumber).change()
    $('#select2-carNumberSelect2-container').attr('title', row.carNumber)
    $('#select2-carNumberSelect2-container').text(row.carNumber)

    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#transportStartDate')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd hh:ii:ss',
            language: 'zh-CN',
            autoclose: true
          })
          .on('changeDate', function (e) {
            var date = e.date
            if (!date) {
              return
            }
            var time = common.getTimeMmss(date)
            $('#transportStartDate').val(time).change()
            that.handleRow.transportStartDate = time
          })

        $('#transportEndDate')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd hh:ii:ss',
            language: 'zh-CN',
            autoclose: true
          })
          .on('changeDate', function (e) {
            var date = e.date
            if (!date) {
              return
            }
            var time = common.getTimeMmss(date)
            $('#transportEndDate').val(time).change()
            that.handleRow.transportEndDate = time
          })
        // var date = new Date();
        // $("#datetimepicker2").val(that.getTime(date));//当前时间
        // date.setDate(date.getDate() - 7);//设置前一周
        // $("#datetimepicker1").val(that.getTime(date));
      })
    })

    $('#rowDataForm').data('bootstrapValidator').resetForm()
  }
  cancelEdit(val) {
    val.hide()
    $('#rowDataForm').data('bootstrapValidator').resetForm()
  }
  editSubmit(val) {
    $('#rowDataForm').bootstrapValidator('validate')
    let isValid = $('#rowDataForm').data('bootstrapValidator').isValid()
    if (isValid) {
      this.jsonApiService
        .http_obj('weighbridgeVerify/V2/updateWeighbridgeVerify.html', this.handleRow)
        .subscribe(result => {
          this.jsonApiService.message(result.message)
          if (result.success) {
            this.load()
            this.cancelEdit(val)
          }
        })
    }
  }

  // 页面跳转
  jumpPage(Url, row) {
    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('weighbridgeDataResult', JSON.stringify(row))
    window.open(BaseURL + '#' + Url)
  }
}
